package com.jbbmobile.hackathon.GWT.RPC.server;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.jbbmobile.hackathon.GWT.RPC.client.PersonService;
import com.jbbmobile.hackathon.Model.Person;

public class PersonServiceImpl extends RemoteServiceServlet implements PersonService {
	private static final long serialVersionUID = -3319556603058089747L;
	private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	private static final Logger log = Logger.getLogger(PersonServiceImpl.class.getName());
	public void createPerson(String name, String phone, String email, String address, int type) throws Exception {
		Objectify ob = ObjectifyService.begin();
		URL setWo;
		try {
			setWo = new URL("http://maps.google.com/maps/api/geocode/xml?address="+address.replace(' ', '+') + "," +
				"toronto,ontario" + "&sensor=false");
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(setWo.openStream());
			doc.normalize();
			double latitude = Double.parseDouble(doc.getElementsByTagName("lat").item(0).getChildNodes().item(0).getNodeValue());
			double longtitude = Double.parseDouble(doc.getElementsByTagName("lng").item(0).getChildNodes().item(0).getNodeValue());
			Person p = new Person(name, phone, email, address, type);
			p.setLatitude(latitude);
			p.setLongtitude(longtitude);
			ob.put(p);
		} catch (MalformedURLException e) {
			log.warning(e.toString());
			throw new Exception(e.getMessage());
		} catch (SAXException e) {
			log.warning(e.toString());
			throw new Exception(e.getMessage());
		} catch (IOException e) {
			log.warning(e.toString());
			throw new Exception(e.getMessage());
		} catch (ParserConfigurationException e) {
			log.warning(e.toString());
			throw new Exception(e.getMessage());
		}
	}
}
